package com.ruoyi.common.cos.controller;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.cos.po.ChunkedUploadPo;
import com.ruoyi.common.cos.po.UploadTextToCOSPo;
import com.ruoyi.common.cos.service.CosService;
import com.ruoyi.common.utils.OrderUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * COS腾讯云存储上传
 */
@RestController
@RequestMapping("/cos")
@Anonymous
public class CosController {

    @Autowired
    private CosService cosService;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file) throws IOException {

        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        String key = getKey("/profile/upload/", originalFilename);

        // 将 MultipartFile 转换为 File
        File tempFile = File.createTempFile("upload-", originalFilename);
        file.transferTo(tempFile);

        Map<String, String> stringStringMap = cosService.uploadFile(tempFile, key);

        // 上传文件并返回文件URL
        return AjaxResult.success().put("fileName",stringStringMap.get("fileName")).put("url",stringStringMap.get("url")) ;
    }

    private String getKey(String catalogue, String originalFilename) {
        // 获取当前日期的年、月、日
        LocalDate today = LocalDate.now();
        String year = String.valueOf(today.getYear());
        String month = String.format("%02d", today.getMonthValue()); // 保证月份是两位数
        String day = String.format("%02d", today.getDayOfMonth()); // 保证日期是两位数

        // 生成文件存储路径，例如：year/month/day
        String path = catalogue + year + "/" + month + "/" + day + "/";

        // 生成带路径的文件名
        return path + originalFilename;
    }


    /**
 * 文本上传
 */
    @PostMapping("/stringUpload")
    public AjaxResult stringUpload(@RequestBody UploadTextToCOSPo text) throws IOException {
        String key = getKey("/profile/upload/", OrderUtils.getOrderNo("WB") + ".txt");
        // 将文本内容转换为文件
        File tempFile = File.createTempFile("upload-", ".txt");
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile))) {
            writer.write(text.getText());
        }

        // 上传文件到 COS
        Map<String, String> stringStringMap = cosService.uploadFile(tempFile, key);

        // 返回文件名和文件 URL
        return AjaxResult.success().put("fileName", stringStringMap.get("fileName"))
                .put("url", stringStringMap.get("url"));
    }

    /**
     * 下载文件
     */
    @GetMapping("/download/{fileName}")
    public COSObject download(@PathVariable String fileName) {
        return cosService.downloadFile(fileName);
    }

     /**
     * 获取文本内容
     */
    @GetMapping("/someMethod")
    public AjaxResult someMethod(@RequestParam String fileUrl) {
        return AjaxResult.success().put("text",cosService.getTextFromFile(fileUrl));
    }



    /**
     * 通过 URL 上传文件到 COS
     * @param fileUrl 文件的 URL 地址
     * @param fileName 存储在 COS 上的文件名
     * @return COS 上的文件访问 URL
     */
    @PostMapping("/uploadFromUrl")
    public String uploadFromUrl(@RequestParam("fileUrl") String fileUrl,
                                @RequestParam("fileName") String fileName) throws IOException {
        return cosService.uploadFileFromUrl(fileUrl, fileName);
    }


    /**
     * 接收文件分块并上传
     * @param file 上传的文件块
//     * @param uploadId 唯一标识每次上传
     * @param chunkIndex 当前块的索引
     * @param totalChunks 总块数
     * @param fileName 上传文件的名称
     * @throws IOException
     */
    @PostMapping("/chunkedUpload")
    public AjaxResult chunkedUpload(@RequestParam("file") MultipartFile file,
                                    @RequestParam("uploadId") String uploadId,
                                    @RequestParam("chunkIndex") int chunkIndex,
                                    @RequestParam("totalChunks") int totalChunks,
                                    @RequestParam("fileName") String fileName) throws IOException {

        Map<String, Object> result = cosService.uploadFileChunk(file, uploadId, chunkIndex, totalChunks, getKey("/profile/video/", fileName));
        return AjaxResult.success().put("data",result);
    }


    /**
    * 接收文件整个文件
    * @param file 上传的文件
    */
    @PostMapping("/chunkedUploadFile")
    public AjaxResult chunkedUpload(@RequestParam("file") MultipartFile file) throws IOException {

        String key = getKey("/profile/video/", file.getOriginalFilename());
        return AjaxResult.success().put("data",cosService.uploadFileInChunks(file, key));
    }


    /**
     * 获取ID
     * @param fileName 文件名称
     * @return
     */
    @GetMapping("/getUploadId")
    public AjaxResult getUploadIdList(@RequestParam String fileName) {
        // 返回 PartListing 对象的字符串表示
        return AjaxResult.success().put("data",cosService.getUploadId(getKey("/profile/video/", fileName)));
    }


    /**
     * 合并
     * @param chunkedUploadPo 文件名称
     * @return
     */
    @PostMapping("/mergeFile")
    public AjaxResult mergeFile(@RequestBody ChunkedUploadPo chunkedUploadPo){
        cosService.mergeFile(chunkedUploadPo.getUploadId(),chunkedUploadPo.getTotalChunks(),chunkedUploadPo.getKey(),chunkedUploadPo.getListETag());

        // 返回 PartListing 对象的字符串表示
        return AjaxResult.success();
    }

    /**
     * 获取临时ID
     * @return
     */
    @GetMapping("/getKeyAndCredentials")
    public AjaxResult getKeyAndCredentials(){


        // 返回 PartListing 对象的字符串表示
        return AjaxResult.success().put("data",cosService.getUploadIdTemporary());
    }







}
